module WindSpirit
{
    /*
    序列帧播放封装类
    */
    export class FrameConfig
    {
        name: string;//资源名前缀
        frameRate: number;//帧率
        frameNum: number;//帧数
        isLoop: boolean = false;//是否循环播放
        numLen: number = 0;//有效数字(不足补零)
        endFunc: Function = null;//播放完成回调函数
        start: number = 0;//起始前缀
    }
    export class FramePlay extends egret.DisplayObjectContainer
    {
        private _frame: egret.Bitmap;
        private _config: FrameConfig;
        private _timer: egret.Timer;
        private _curFrameIndex: number = 0;
        public constructor(config: FrameConfig)
        {
            super();
            this._config = config;
            this._frame = new egret.Bitmap;
            this.setFrame();
            this.addChild(this._frame);
            this._timer = new egret.Timer(1000 / this._config.frameRate);
            this._timer.addEventListener(egret.TimerEvent.TIMER,this.update,this);
        }
        public play(): void
        {
            this._timer.start();
        }
        public stop(): void
        {
            this._timer.stop();
        }
        public update(event: egret.Event): void
        {
            this.setFrame();
            if(this._curFrameIndex == this._config.frameNum - 1)
            {
                if(this._config.endFunc)
                {
                    this._config.endFunc();
                }
                if(!this._config.isLoop)
                {
                    this._timer.stop();
                    return;
                }
            }
            this._curFrameIndex++;
            this._curFrameIndex %= this._config.frameNum;
        }
        public setFrame(): void
        {
            var curName: number = (this._curFrameIndex + this._config.start);
            var res;
            if(this._config.numLen > 0)
            {
                res = this._config.name + this.appendZero(curName,this._config.numLen);
            }
            else
            {
                res = this._config.name + curName;
            }
            this._frame.texture = RES.getRes(res);
        }
        public appendZero(num: number,len: number): string
        {
            var numStr = num.toString();
            var startlen = numStr.length;
            for(var i = startlen;i < len;i++)
            {
                numStr = "0" + numStr;
            }
            return numStr;
        }
    }
}